package com.wanrue.prometheus.service.impl;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.naming.NamingService;
import com.wanrue.prometheus.properties.DiscoveryConfig;
import com.wanrue.prometheus.service.ApiService;
import com.wanrue.prometheus.pojo.Instance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import java.util.*;

@Slf4j
public class NacosApiService implements ApiService, InitializingBean, DisposableBean {

    private NamingService namingService;

    private final DiscoveryConfig discoveryConfig;

    public NacosApiService(DiscoveryConfig discoveryConfig) {
        this.discoveryConfig = discoveryConfig;
    }

    @Override
    public List<Instance> discovery(String service) throws Exception {
        List<Instance> instanceList = new ArrayList<>();
        namingService.registerInstance(service, "192.168.52.196", 8080);
        List<com.alibaba.nacos.api.naming.pojo.Instance> instances = namingService.getAllInstances(service);
        for (com.alibaba.nacos.api.naming.pojo.Instance in : instances) {
            Instance instance = new Instance();
            instance.setTargets(Arrays.asList(in.toInetAddr()));
            instance.setLabels(new HashMap<>());
            instanceList.add(instance);
        }
        return instanceList;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, discoveryConfig.getNacos().getServerAddr());
        properties.setProperty(PropertyKeyConst.NAMESPACE, discoveryConfig.getNacos().getNamespace());
        this.namingService = NacosFactory.createNamingService(properties);
    }


    @Override
    public void destroy() throws Exception {
        namingService.shutDown();
    }
}
